package com.example.demo.aop;

import com.auth0.jwt.JWT;
import com.example.demo.jwt.CheckToken;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * Created by mazeyi on 2019/12/6.
 */
@Aspect
@Component
public class ApioathAop {

    @Pointcut(value = "@annotation(com.example.demo.jwt.CheckToken)")
    private void checkToken() {

    }

    @Around("checkToken()")
    public Object checkToken(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method method = ms.getMethod();
        CheckToken checkToken = method.getAnnotation(CheckToken.class);
        boolean flag = checkToken.required();

        if (flag) {
            // 开始检验token
            Class[] paramTypes = ms.getParameterTypes();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

           // User user = new User();
            // 从 http 请求头中取出 token
            String token = request.getHeader("token");
            if (token == null) {
                throw new RuntimeException("token验证失败");
            }
            String name;
            name = JWT.decode(token).getClaim("username").asString();

           // boolean isChecked = JwtUtil.checkToken(token, user);

         /*   if (!isChecked) {
                throw new RuntimeException("非法访问");
            }*/
            return joinPoint.proceed();
        } else {
            return joinPoint.proceed();
        }
    }
}